<template>
  <view class="appointmentDoctorInfoConfirm-page">
    <NavBar title="医生详情" />

    <view class="list">
      <!-- 医生信息 -->
      <view class="doctor-info">
        <view class="content">
          <Image class="avatar" :src="doctorInfo?.avatarUrl" />

          <view class="content-info">
            <view class="name">
              <text class="name-text">{{ doctorInfo?.doctorName }}</text>

              <text class="name-label">{{
                doctorInfo?.gender === "1"
                  ? "男"
                  : doctorInfo?.gender === "2"
                  ? "女"
                  : "未知"
              }}</text>
              <text class="name-label">{{ doctorInfo?.title }}</text>
            </view>

            <view class="desc">
              <text class="desc-text">{{ doctorInfo?.notes }}</text>
            </view>
          </view>
        </view>
      </view>

      <!-- 就诊日期 预估就诊时间 挂号费 -->
      <view class="rows">
        <view class="row">
          <view class="label">就诊日期</view>

          <view class="value text"> {{ visitDate }} </view>
        </view>

        <view class="row">
          <view class="label">预估就诊时间</view>

          <view class="value text"> {{ visitTime }} </view>
        </view>

        <view class="row">
          <view class="label">挂号费</view>

          <view class="value red"
            >{{
              doctorInfo?.appointmentFee
                ? (doctorInfo?.appointmentFee / 100).toFixed(2)
                : "0.00"
            }}元</view
          >
        </view>
      </view>

      <!-- 有就诊人信息时显示 -->
      <view class="user-info" v-if="userState.currentPatient">
        <view class="block">
          <view class="title">
            <view class="text">就诊人信息</view>
            <view class="edit" @tap="handleSelectPatient" v-if="!isSuccess"
              >更换就诊人</view
            >
          </view>

          <view class="row mb">
            姓ㅤㅤ名：{{ userState.currentPatient?.patientName }}
          </view>

          <view class="row">
            证件号码：{{ idCardFormat(userState.currentPatient?.idCard ?? "") }}
          </view>
        </view>

        <view class="tips" v-if="!isSuccess">
          <view class="title">温馨提示：</view>

          <view class="content">
            1、爽约：本周内累计爽约达2次，限制手机预约，但不影响到院后现场当日挂号
          </view>
        </view>

        <view class="footer" v-if="!isSuccess">
          <view class="footer-btn" @tap="handleConfirm"> 确认预约 </view>
        </view>
      </view>

      <!-- 无就诊人信息时显示 -->
      <view class="no-user-info" v-else>
        <view class="block">
          <view class="text"> 请先填写就诊人信息 </view>

          <view class="btn" @tap="handleToPatientsInfo"> 填写就诊人 </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import dayjs from "dayjs";
import Taro, { useReady, useRouter } from "@tarojs/taro";
import NavBar from "../../components/NavBar.vue";
import { useAppointmentStore } from "../../stores/appointmentStore";
import { useUserStore } from "../../stores/userStore";
import { ref, computed } from "vue";
import { RemainListRes } from "../../../types/appointment.type";
import { idCardFormat } from "../../utils/format.util";
import { addAppointment } from "../../api/appointment.api";

const router = useRouter();
const appointmentState = useAppointmentStore();
const userState = useUserStore();
const query = ref<{
  doctorId: number | undefined;
  deptId: number | undefined;
  date: number | undefined;
  period: string | undefined;
  visitSeqNo: number | undefined;
}>({
  doctorId: undefined,
  deptId: undefined,
  date: undefined,
  period: undefined,
  visitSeqNo: undefined,
});
const doctorInfo = ref<RemainListRes>();
const loading = ref(false);
// 是否预约成功
const isSuccess = ref(false);

const dateNames = {
  Tomorrow: "明天",
  Monday: "周一",
  Tuesday: "周二",
  Wednesday: "周三",
  Thursday: "周四",
  Friday: "周五",
  Saturday: "周六",
  Sunday: "周日",
};

// 就诊日期格式化
const visitDate = computed(() => {
  const period = doctorInfo.value?.periodList.find(
    (item) => item.value.toString() === query.value.period?.toString()
  );

  // 星期几
  const week = dayjs(query.value.date).format("dddd");

  return (
    dayjs(query.value.date).format("YYYY年MM月DD日") +
    " " +
    dateNames[week as keyof typeof dateNames] +
    " " +
    period?.text
  );
});

// 预估就诊时间
const visitTime = computed(() => {
  const period = doctorInfo.value?.periodList.find(
    (item) => item.value.toString() === query.value.period?.toString()
  );

  const detail = period?.detailList.find(
    (item) => item.visitSeqNo.toString() === query.value.visitSeqNo?.toString()
  );

  return detail?.startTime;
});

// 更换就诊人
const handleSelectPatient = () => {
  Taro.navigateTo({
    url: "/pages/selectPatients/selectPatients",
  });
};

// 获取就诊人列表
const getPatientListApi = async () => {
  // 获取就诊人列表
  if (!userState.patientList.length) {
    await userState.getPatientListApi();
  }

  const patient = userState.patientList.find((item) => item.isDefault === "1");

  // 设置当前就诊人
  if (patient) {
    userState.currentPatient = patient;
  }
  // 如果没有默认就诊人，则设置第一个就诊人
  else if (userState.patientList.length) {
    userState.currentPatient = userState.patientList[0];
  }
};

// 确认预约
const handleConfirm = async () => {
  if (loading.value) return;

  try {
    loading.value = true;

    const res = await addAppointment({
      visitDate: dayjs(query.value.date).format("YYYY-MM-DD"),
      visitPeriod: query.value.period!,
      visitSeqNo: query.value.visitSeqNo!,
      doctorId: query.value.doctorId!,
      patientId: userState.currentPatient?.patientId!,
    });

    if (res.code === "200") {
      Taro.showToast({
        title: "预约成功",
        icon: "success",
      });

      isSuccess.value = true;
    } else {
      Taro.showToast({
        title: res.msg,
        icon: "none",
      });
    }
  } catch (error) {
    console.error(error);
  } finally {
    loading.value = false;
  }
};

// 填写就诊人
const handleToPatientsInfo = () => {
  Taro.navigateTo({
    url: "/pages/patientsInfo/patientsInfo?type=doctorAdd",
  });
};

useReady(() => {
  if (router.params.doctorId) {
    query.value.doctorId = Number(router.params.doctorId);
  }

  if (router.params.deptId) {
    query.value.deptId = Number(router.params.deptId);
  }

  if (router.params.date) {
    query.value.date = Number(router.params.date);
  }

  // 上午 | 下午 | 晚上
  if (router.params.period) {
    query.value.period = router.params.period;
  }

  // 排队序号
  if (router.params.visitSeqNo) {
    query.value.visitSeqNo = Number(router.params.visitSeqNo);
  }

  const info =
    appointmentState.remainData[dayjs(query.value.date).format("YYYY-MM-DD")];

  if (info) {
    doctorInfo.value = info.find(
      (item) => item.doctorId === query.value.doctorId
    );
  }

  // 获取就诊人列表
  getPatientListApi();
});
</script>

<style lang="scss">
.appointmentDoctorInfoConfirm-page {
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100vh;
  background: #ffffff;

  .list {
    flex: 1;
    display: flex;
    flex-direction: column;
    width: 100%;
    background: #ffffff;
    overflow-y: auto;
    position: relative;

    .doctor-info {
      width: 100%;

      .content {
        display: flex;
        align-items: flex-start;
        width: 100%;
        padding: 20px 16px;

        .avatar {
          flex-shrink: 0;
          width: 43px;
          height: 64px;
          border-radius: 4px;
        }

        .content-info {
          flex: 1;
          display: flex;
          flex-direction: column;
          gap: 5px;
          padding-left: 20px;

          .name {
            display: flex;
            align-items: center;
            gap: 10px;

            .name-text {
              font-weight: bold;
              font-size: 18px;
              color: #06202e;
              line-height: 18px;
              font-style: normal;
            }

            .name-label {
              font-weight: 400;
              font-size: 13px;
              color: #777777;
              line-height: 13px;
              font-style: normal;
            }
          }

          .desc {
            width: 100%;
            font-weight: 400;
            font-size: 13px;
            color: #777777;
            text-align: left;
            font-style: normal;
            text-transform: none;
          }
        }
      }
    }

    .rows {
      display: flex;
      flex-direction: column;
      gap: 8px;
      width: 100%;
      padding: 0px 16px;

      .row {
        display: flex;
        align-items: center;
        justify-content: space-between;
        width: 100%;
        padding: 16px 0px;
        border-bottom: 1px solid #f5f6fa;

        .label {
          font-weight: 400;
          font-size: 14px;
          color: #333333;
          font-style: normal;
        }

        .value {
          &.text {
            font-weight: 400;
            font-size: 14px;
            color: #333333;
            font-style: normal;
          }

          &.red {
            font-weight: 400;
            font-size: 14px;
            color: #d90000;
            font-style: normal;
          }
        }
      }
    }

    .user-info {
      flex: 1;
      display: flex;
      flex-direction: column;
      gap: 16px;
      width: 100%;
      padding: 16px 14px;
      padding-bottom: 0px;

      .block {
        display: flex;
        flex-direction: column;
        width: 100%;
        padding: 15px 16px;
        background: #f8fbff;
        border-radius: 12px;

        .title {
          display: flex;
          align-items: center;
          justify-content: space-between;
          width: 100%;
          padding-bottom: 15px;

          .text {
            font-weight: 500;
            font-size: 16px;
            color: #333333;
            text-align: left;
            font-style: normal;
            text-transform: none;
          }

          .edit {
            font-weight: 400;
            font-size: 13px;
            color: #16ada4;
            text-align: right;
            font-style: normal;
            text-transform: none;
          }
        }

        .row {
          font-weight: 400;
          font-size: 13px;
          color: #333333;
          font-style: normal;

          &.mb {
            padding-bottom: 13px;
          }
        }
      }

      .tips {
        display: flex;
        flex-direction: column;
        gap: 6px;
        width: 100%;
        padding: 0px 14px;

        .title {
          font-weight: bold;
          font-size: 13px;
          color: #aaaaaa;
          font-style: normal;
        }

        .content {
          font-weight: 400;
          font-size: 13px;
          color: #aaaaaa;
          font-style: normal;
        }
      }

      .footer {
        flex-shrink: 0;
        width: 100%;
        margin-top: auto;
        padding: 30px 16px;

        .footer-btn {
          display: flex;
          align-items: center;
          justify-content: center;
          width: 100%;
          height: 45px;
          background: #16ada4;
          border-radius: 30px;
          font-weight: 400;
          font-size: 16px;
          color: #ffffff;
          line-height: 24px;
          font-style: normal;
        }
      }
    }

    .no-user-info {
      width: 100%;
      padding: 16px 14px;

      .block {
        display: flex;
        align-items: center;
        justify-content: space-between;
        width: 100%;
        height: 54px;
        padding: 0px 16px;
        background: #f8fbff;
        border-radius: 12px 12px 12px 12px;

        .text {
          font-weight: 500;
          font-size: 16px;
          color: #333333;
          font-style: normal;
        }

        .btn {
          font-weight: 400;
          font-size: 13px;
          color: #16ada4;
          font-style: normal;
        }
      }
    }
  }
}
</style>
